#生成字典
def getdict():
    t1 = [x for x in range(26)]
    t2 = []
    for i in range(26):
        k = [chr(65+(i+k)%26) for k in range(26)]
        t2.append(k)
    dic = dict(zip(t1, t2))
    return dic

#最后一行没有换行符，去除非字母字符。存在列表里
def normal(filename, length):
    with open(filename, 'r') as fp:
        output = []
        item = []
        while True:
            ch = fp.read(1)
            if not ch:
                if item:
                    output.append(item)
                break
            else:
                if ch.isalpha():
                    item.append(ch)
                    if len(item) == length:
                        output.append(item)
                        item = []
        #if not item:
            #output.append(item)
        #print(output)
        return output

def encrypt():
    dic = getdict()
    key = list(input("Please input the key: "))
    inputname = input("Please input the name of plaintext: ")
    outputname = input("Please input the name of cipher text you want to get: ")
    inputplain = normal(inputname, len(key))
    with open(outputname, 'w') as fp:
        for plain in inputplain:
            for i in range(len(plain)):
                ch = dic[ord(key[i]) - ord('a')][ord(plain[i].lower()) - ord('a')]
                fp.write(ch)

def decode():
    dic = getdict()
    key = list(input("Please input the key: "))
    inputname = input("Please input the name of cipher text: ")
    outputname = input("Please input the name of plain text you want to get: ")
    dic = getdict()
    with open(outputname, 'w') as cp:
        items = normal(inputname, len(key))
        for item in items:
            for i in range(len(item)):
                element = dic[ord(key[i]) - ord('a')].index(item[i])
                ch = chr(element + ord('a'))
                cp.write(ch)



